import json

def format_channel_name(name):
    if name.startswith('CCTV'):
        return name.split('-')[0]
    if name == "东南卫视":
        return "福建东南卫视"
    return name

def extract_channel_name(extinf_line):
    # 处理包含tvg-id等元数据的情况
    if 'tvg-name=' in extinf_line:
        # 找到最后一个逗号后的内容作为频道名
        name = extinf_line.split(',')[-1].strip()
    else:
        # 处理简单格式的情况
        name = extinf_line.split(',')[1].strip()
    return name

def fill_pd_json():
    pd_json_path = 'pd.json'
    with open(pd_json_path, 'r', encoding='utf-8') as f:
        pd_json = json.load(f)

    choice = input("是否要删除频道的URL（y/n）: ")
    if choice.lower() == 'y':
        for channel in pd_json:
            # 创建要删除的键的列表
            keys_to_delete = []
            for key in channel.keys():
                if key.startswith('url'):
                    keys_to_delete.append(key)
            # 删除收集到的键
            for key in keys_to_delete:
                channel.pop(key, None)
        print("已删除所有频道的URL。")
        # 立即保存更改
        with open(pd_json_path, 'w', encoding='utf-8') as f:
            json.dump(pd_json, f, indent=4, ensure_ascii=False)

    m3u_count = 1
    while True:
        empty_url_channels = []
        for channel in pd_json:
            url_keys = [k for k in channel.keys() if k.startswith('url')]
            all_url_empty = True
            for url_key in url_keys:
                if channel[url_key]:
                    all_url_empty = False
                    break
            if all_url_empty:
                empty_url_channels.append(channel["name"])
        print(f"在处理第{m3u_count}个.m3u文件之前，pd.json 中url为空的频道: {empty_url_channels}")

        m3u_file_path = input(f"请输入第{m3u_count}个.m3u文件的路径（如果没有更多文件请输入'q'退出）: ")
        if m3u_file_path == 'q':
            break

        m3u_url_dict = {}
        with open(m3u_file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            i = 0
            while i < len(lines):
                if lines[i].startswith('#EXTINF'):
                    name = format_channel_name(extract_channel_name(lines[i]))
                    url = lines[i + 1].strip()
                    if name not in m3u_url_dict:
                        m3u_url_dict[name] = [url]
                    else:
                        m3u_url_dict[name].append(url)
                    i += 1
                i += 1
            print(m3u_url_dict)

        no_url_channels = []
        replaced_channels = []
        for channel in pd_json:
            if "name" in channel:
                formatted_name = format_channel_name(channel["name"])
                if formatted_name in m3u_url_dict:
                    url_list = m3u_url_dict[formatted_name]
                    if "url" not in channel and url_list:
                        channel["url"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url1" not in channel and url_list:
                        channel["url1"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url2" not in channel and url_list:
                        channel["url2"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url3" not in channel and url_list:
                        channel["url3"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url4" not in channel and url_list:
                        channel["url4"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url5" not in channel and url_list:
                        channel["url5"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                else:
                    no_url_channels.append(channel["name"])

        with open(pd_json_path, 'w', encoding='utf-8') as f:
            json.dump(pd_json, f, indent=4, ensure_ascii=False)
        print(f"在处理{m3u_file_path}时，已替换的频道: {replaced_channels}")
        print(f"在处理{m3u_file_path}时，没有传入url的频道: {no_url_channels}")
        m3u_count += 1

if __name__ == "__main__":
    fill_pd_json()
# import json
#
# def format_channel_name(name):
#     if name.startswith('CCTV'):
#         return name.split('-')[0]
#     if name == "东南卫视":
#         return "福建东南卫视"
#     return name
#
# def extract_channel_name(extinf_line):
#     # 处理包含tvg-id等元数据的情况
#     if 'tvg-name=' in extinf_line:
#         # 找到最后一个逗号后的内容作为频道名
#         name = extinf_line.split(',')[-1].strip()
#     else:
#         # 处理简单格式的情况
#         name = extinf_line.split(',')[1].strip()
#     return name
#
# def fill_pd_json():
#     pd_json_path = 'pd.json'
#     with open(pd_json_path, 'r', encoding='utf-8') as f:
#         pd_json = json.load(f)
#
#     choice = input("是否要删除频道的URL（y/n）: ")
#     if choice.lower() == 'y':
#         for channel in pd_json:
#             keys_to_delete = [k for k in channel.keys() if k.startswith('url')]
#             for key in keys_to_delete:
#                 del channel[key]
#         print("已删除所有频道的URL。")
#
#     m3u_count = 1
#     while True:
#         empty_url_channels = []
#         for channel in pd_json:
#             url_keys = [k for k in channel.keys() if k.startswith('url')]
#             all_url_empty = True
#             for url_key in url_keys:
#                 if channel[url_key]:
#                     all_url_empty = False
#                     break
#             if all_url_empty:
#                 empty_url_channels.append(channel["name"])
#         print(f"在处理第{m3u_count}个.m3u文件之前，pd.json 中url为空的频道: {empty_url_channels}")
#
#         m3u_file_path = input(f"请输入第{m3u_count}个.m3u文件的路径（如果没有更多文件请输入'q'退出）: ")
#         if m3u_file_path == 'q':
#             break
#
#         m3u_url_dict = {}
#         with open(m3u_file_path, 'r', encoding='utf-8') as f:
#             lines = f.readlines()
#             i = 0
#             while i < len(lines):
#                 if lines[i].startswith('#EXTINF'):
#                     name = format_channel_name(extract_channel_name(lines[i]))
#                     url = lines[i + 1].strip()
#                     if name not in m3u_url_dict:
#                         m3u_url_dict[name] = [url]
#                     else:
#                         m3u_url_dict[name].append(url)
#                     i += 1
#                 i += 1
#             print(m3u_url_dict)
#
#         no_url_channels = []
#         replaced_channels = []
#         for channel in pd_json:
#             if "name" in channel:
#                 formatted_name = format_channel_name(channel["name"])
#                 if formatted_name in m3u_url_dict:
#                     url_list = m3u_url_dict[formatted_name]
#                     if "url" not in channel and url_list:
#                         channel["url"] = url_list.pop(0)
#                         replaced_channels.append(channel["name"])
#                     elif "url1" not in channel and url_list:
#                         channel["url1"] = url_list.pop(0)
#                         replaced_channels.append(channel["name"])
#                     elif "url2" not in channel and url_list:
#                         channel["url2"] = url_list.pop(0)
#                         replaced_channels.append(channel["name"])
#                     elif "url3" not in channel and url_list:
#                         channel["url3"] = url_list.pop(0)
#                         replaced_channels.append(channel["name"])
#                     elif "url4" not in channel and url_list:
#                         channel["url4"] = url_list.pop(0)
#                         replaced_channels.append(channel["name"])
#                     elif "url5" not in channel and url_list:
#                         channel["url5"] = url_list.pop(0)
#                         replaced_channels.append(channel["name"])
#                 else:
#                     no_url_channels.append(channel["name"])
#
#         with open(pd_json_path, 'w', encoding='utf-8') as f:
#             json.dump(pd_json, f, indent=4, ensure_ascii=False)
#         print(f"在处理{m3u_file_path}时，已替换的频道: {replaced_channels}")
#         print(f"在处理{m3u_file_path}时，没有传入url的频道: {no_url_channels}")
#         m3u_count += 1
#
# if __name__ == "__main__":
#     fill_pd_json()